package info.liujiachen.test.spring.security.config;

import info.liujiachen.test.spring.security.filter.JwtAuthenticationFilter;
import info.liujiachen.test.spring.security.filter.JwtUsernamePasswordAuthenticationFilter;
import info.liujiachen.test.spring.security.service.JwtUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.session.data.redis.config.annotation.SpringSessionRedisConnectionFactory;

@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@SpringSessionRedisConnectionFactory
public class JwtSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtUserDetailsService service;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(this.service);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()
                .and().csrf().disable()
                .formLogin().disable()
                .rememberMe().disable()
                .sessionManagement().disable()
                .authorizeRequests().antMatchers("/api/**").authenticated()
                .and().authorizeRequests().antMatchers("/api/admin/login").permitAll()
                .and().addFilterBefore(new JwtUsernamePasswordAuthenticationFilter(authenticationManagerBean(), "/api/admin/login"), UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(new JwtAuthenticationFilter(authenticationManagerBean()), BasicAuthenticationFilter.class)
                .logout().logoutUrl("/api/admin/logout")
                .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
